Valid Parentheses

Given a string containing just the characters '(', ')', '{', '}', '[' and ']',
determine if the input string is valid.
The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.

题目大意:判断括号是否闭合

题目难度:Easy

/**
 * Created by gzdaijie on 16/5/6
 * 堆栈匹配栈顶和当前字符是否匹配,若栈顶是 }、]、) 直接返回false
 */
public class Solution {
    public boolean isValid(String s) {
        if (s == null || s.length() == 1)return false;

        int len = s.length();
        Stack stack = new Stack(len);
        for (int i = 0; i < len; i++) {
            char ch = s.charAt(i);
            if (stack.isEmpty()) {
                stack.push(s.charAt(i));
            } else {
                char peek = stack.peek();
                if (peek == '}' || peek == ']' || peek == ')') return false;
                if (peek == '{' && ch == '}' || peek == '[' && ch == ']' || peek == '(' && ch == ')') {
                    stack.pop();
                } else {
                    stack.push(ch);
                }
            }
        }
        return stack.isEmpty();
    }

    private class Stack {
        char[] stack;
        int index = -1;
        Stack(int n) {
            this.stack = new char[n];
        }
        public void push(char ch) {
            this.stack[++this.index] = ch;
        }
        public char pop() {
            --this.index;
            return this.stack[index + 1];
        }
        public boolean isEmpty() {
            return this.index == -1;
        }
        public char peek() {
            return this.stack[this.index];
        }
    }
}
import java.util.Stack;

/**
 * Created by gzdaijie on 16/5/6
 * 利用标准库及 ()相差一 []相差二的特性
 */
public class Solution {
    public boolean isValid(String s) {
        if (s == null || s.length() == 1) return false;

        int len = s.length();
        Stack<Character> stack = new Stack<Character>();
        for (int i = 0; i < len; i++) {
            char ch = s.charAt(i);
            if (ch == '(' || ch == '{' || ch == '[') stack.push(ch);
            else if (!stack.isEmpty() &&  Math.abs(ch - stack.peek()) <= 2) stack.pop();
            else return false;
        }
        return stack.isEmpty();
    }
}
gzdaijie            updated 2016-05-07 01:01:37

results matching ""

    No results matching ""